<?php

namespace App\Admin\Actions\Good;

use App\Admin\Services\GoodService;
use App\Jobs\DownImageJob;
use App\Model\ExportGoodJob;
use App\Model\ExportGoodJobDetail;
use Box\Spout\Common\Exception\IOException;
use Box\Spout\Reader\Common\Creator\ReaderEntityFactory;
use Box\Spout\Reader\Exception\ReaderNotOpenedException;
use Encore\Admin\Actions\Action;
use Encore\Admin\Actions\Response;
use Encore\Admin\Facades\Admin;
use Illuminate\Http\Request;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;

class Import extends Action
{
    public $name = '导入商品Asin数据';

    protected $selector = '.import-post';

    /**
     * Handle the form request.
     *
     * @param Request $request
     *
     * @return Response
     * @throws IOException
     * @throws ReaderNotOpenedException
     */
    public function handle(Request $request)
    {
        $reader = ReaderEntityFactory::createCSVReader();
        $reader->open($request->file('file'));

        $sheets = $reader->getSheetIterator();
        $sheets->rewind();
        $sheet = $sheets->current();

        $goodAsinArr = [];
        foreach ($sheet->getRowIterator() as $k => $row) {
            $rowArr = $row->toArray();
            $goodAsinArr[] = [
                'sort' => $k,
                'asin' => $rowArr[0]
            ];;
        }
        $reader->close(); // 释放内存

        $goods = app(GoodService::class)->getGoodsIdByAsin(array_column($goodAsinArr, 'asin'));

        if ($goods->isEmpty()) {
            return $this->response()->error('未查询到相关的商品信息')->refresh();
        }
        DB::beginTransaction();
        try {
            $job = ExportGoodJob::query()->create([
                'user_id' => Admin::user()->id
            ]);

            foreach ($goodAsinArr as &$value) {
                $value['good_id'] = $goods->where('asin' , $value['asin'])->first()->good_id ?? 0;
                $value['job_id'] =  $job->id;
            }

            ExportGoodJobDetail::query()->insert($goodAsinArr);
        } catch (\Exception $exception) {
            DB::rollBack();
         
            return $this->response()->error("导入失败：" . $exception->getMessage())->refresh();
        }
        DB::commit();
        // 拉取相关的图片
        $detail = ExportGoodJobDetail::query()
            ->where('job_id', $job->id)
            ->get();

        foreach ($detail as $item) {
            dispatch((new DownImageJob($item->id)));
        }

        return $this->response()->success('正在处理中请稍后，查看')->refresh();
    }

    public function form()
    {
        $this->file('file', '请导入要获取商品信息的Asin数据')->rules('required', [
            'required' => '请上传Asin的csv文件'
        ]);
    }

    public function html()
    {
        return <<<HTML
        <a class="btn btn-sm btn-default import-post"><i class="fa fa-upload"></i>导入Asin数据(获取商品信息)</a>
HTML;
    }

}
